package com.guanzi.server.controller;


import com.guanzi.server.entity.User;
import com.guanzi.server.entity.dto.UserSaveDTO;
import com.guanzi.server.service.IUserService;
import com.guanzi.server.util.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author guanzi
 * @since 2021-06-04
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 查找所有用户
     * @return
     */
    @PostMapping("/list")
    public RespBean getUserList() {
        List<User> list = userService.getUserList();
        return RespBean.success("查找成功！",list);
    }

    @GetMapping("/delete")
    public RespBean deleteUser(@RequestParam("id") Integer id) {
        userService.deleteUser(id);
        return RespBean.success("删除成功！");
    }

    /**
     * 用户信息和图片保存
     * @param userSaveDTO
     * @return
     * @throws IOException
     */
    @PostMapping("/save")
    public RespBean save(UserSaveDTO userSaveDTO) throws IOException {
        userSaveDTO.setImg( Base64Utils.encodeToString(userSaveDTO.getPic().getBytes()) );
        Boolean yOn = userService.updateUser(userSaveDTO);
        if ( yOn ) {
            return RespBean.success("用户信息已保存！", userSaveDTO.getImg());
        }
        return RespBean.error("用户名已被使用！");

//        System.out.println("Base64:" + s);
        //直接将s存储到数据库中就可以了 数据库字段 mediumtext   排序规则utf8_general_ci
        //展示图片base64解码的时候:src data:image/png;base64,后面加上s
        //  <img :src="user.img">
        //
        //  export default {
        //     data() {
        //        icon: 'data:image/png;base64,,XXXXX...',
        //     }
        //  }
    }
}
